import { NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { getUser } from '@/lib/authUtils'

export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
): Promise<Response> {
  try {
    const userid = await getUser(request)
    if (!userid) {
      return new Response(
        JSON.stringify({ error: '未授权或登录信息过期，请登录' }),
        { status: 401 }
      )
    }
    if (userid instanceof NextResponse) {
      return userid
    }

    const { id } = params
    
    const topic = await prisma.vms_topic.findUnique({
      where: { id }
    })
    
    if (!topic) {
      return new Response(
        JSON.stringify({ error: '未找到话题' }),
        { status: 404 }
      )
    }
    
    if (topic.user_id !== userid) {
      return new Response(
        JSON.stringify({ error: '无权删除他人话题' }),
        { status: 403 }
      )
    }

    await prisma.vms_topic.delete({
      where: { id }
    })
    // 删除话题对应的所有文案
    await prisma.vms_copy.deleteMany({
      where: { topic_id: id }
    })

    // 删除话题对应的所有脚本
    await prisma.vms_script.deleteMany({
      where: {
        copy_id: {
          in: (await prisma.vms_copy.findMany({
            where: { topic_id: id },
            select: { id: true }
          })).map(copy => copy.id)
        }
      }
    })
    // 获取话题对应的文案和脚本数量
    const copyCount = await prisma.vms_copy.count({
      where: { topic_id: id }
    })
    
    const scriptCount = await prisma.vms_script.count({
      where: {
        copy_id: {
          in: (await prisma.vms_copy.findMany({
            where: { topic_id: id },
            select: { id: true }
          })).map(copy => copy.id)
        }
      }
    })

    // 更新用户统计信息
    await prisma.vms_user.update({
      where: { id: userid },
      data: {
        topic_count: {
          decrement: 1
        },
        copy_count: {
          decrement: copyCount
        },
        script_count: {
          decrement: scriptCount
        }
      }
    })
    return new Response(
      JSON.stringify({ message: '话题删除成功' }),
      { status: 200 }
    )
  } catch (error: any) {
    return new Response(
      JSON.stringify({ error: error.message || '删除话题失败' }),
      { status: 500 }
    )
  }
}

export async function GET(
  request: Request,
  { params }: { params: { id: string } }
): Promise<Response> {
  try {
    const { id } = params
    
    const topic = await prisma.vms_topic.findUnique({
      where: { id }
    })
    
    if (!topic) {
      return new Response(
        JSON.stringify({ error: '未找到话题' }),
        { status: 404 }
      )
    }
    
    return new Response(
      JSON.stringify(topic),
      { status: 200 }
    )
  } catch (error: any) {
    return new Response(
      JSON.stringify({ error: error.message || '获取话题详情失败' }),
      { status: 500 }
    )
  }
}